package com.whiteape.book.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.hwangjr.rxbus.RxBus;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.contract.BookReadContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.page.PageLoader;
import com.whiteape.book.core.page.PageStyle;
import com.whiteape.book.core.page.PageView;
import com.whiteape.book.core.page.TxtChapter;
import com.whiteape.book.model.dto.DownloadTaskBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.dto.MediaRecordBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.presenter.BookReadPresenter;
import com.whiteape.book.ui.adapter.BookCatalogAdapter;
import com.whiteape.book.ui.base.BaseMVPActivity;
import com.whiteape.book.ui.dialog.BookReadSettingDialog;
import com.whiteape.book.utils.BrightnessUtils;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.ScreenUtils;
import com.whiteape.book.utils.SimilarityUtil;
import com.whiteape.book.utils.StatusBarCompat;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.SystemBarUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

import static android.view.View.GONE;
import static android.view.View.LAYER_TYPE_SOFTWARE;
import static android.view.View.VISIBLE;

/**
 * Created by newbiechen on 17-5-16.
 */

public class BookReadActivity extends BaseMVPActivity<BookReadContract.Presenter>
        implements BookReadContract.View {
    private static final String TAG = "BookReadActivity";
    public static final int REQUEST_MORE_SETTING = 1111;
    public static final int REQUEST_CHANGE_TYPEFACE = LoadFileType.FILE_TYPE_TYPEFACE;
    public static final int REQUEST_CHANGE_SOURCE = 2222;
    public static final String EXTRA_SHELF_BOOK = "extra_shelf_book";
    public static final String EXTRA_IS_IN_SHELF = "extra_is_in_shelf";
    public static final String EXTRA_CHAPTER_LIST = "extra_chapter_list";
    public static final String EXTRA_JUMP_TO_CHAPTER_INDEX = "extra_jump_to_chapter_index";
    public static final String EXTRA_JUMP_TO_CHAPTER_TITLE = "extra_jump_to_chapter_title";
    public static final String EXTRA_JUMP_TO_CHAPTER_PAGE = "extra_jump_to_chapter_page";

    // 注册 Brightness 的 uri
    private final Uri BRIGHTNESS_MODE_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
    private final Uri BRIGHTNESS_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
    private final Uri BRIGHTNESS_ADJ_URI =
            Settings.System.getUriFor("screen_auto_brightness_adj");

    private static final int WHAT_CATEGORY = 1;
    private static final int WHAT_CHAPTER = 2;
    private static final int WHAT_AUTO_READ_PROGRESS_ADD = 3;

    private static final int AUTO_SPEED_MAX = 20;
    private static final int AUTO_SPEED_MIN = 1;


    @BindView(R.id.read_dl_slide)
    DrawerLayout mDlSlide;
    @BindView(R.id.read_rl)
    RelativeLayout mReadWrapper;
    /*************top_menu_view*******************/
    @BindView(R.id.read_abl_top_menu)
    AppBarLayout mAblTopMenu;

    @BindView(R.id.read_ll_bottom_auto_read_menu)
    LinearLayout mAutoReadMenu;
//    @BindView(R.id.read_tv_community)
//    TextView mTvCommunity;
//    @BindView(R.id.read_tv_brief)
//    TextView mTvBrief;
    /***************content_view******************/
    @BindView(R.id.read_pv_page)
    PageView mPvPage;
    /***************bottom_menu_view***************************/
    @BindView(R.id.read_tv_page_tip)
    TextView mTvPageTip;

    @BindView(R.id.read_ll_bottom_menu)
    LinearLayout mLlBottomMenu;
    @BindView(R.id.read_tv_pre_chapter)
    TextView mTvPreChapter;
    @BindView(R.id.read_sb_chapter_progress)
    SeekBar mSbChapterProgress;
    @BindView(R.id.read_tv_next_chapter)
    TextView mTvNextChapter;
    @BindView(R.id.read_tv_catalog)
    TextView mTvCategory;
    @BindView(R.id.read_tv_night_mode)
    TextView mTvNightMode;
    @BindView(R.id.read_tv_download)
    TextView mTvDownload;
    @BindView(R.id.read_tv_change_source)
    TextView mTvChangeSource;
    @BindView(R.id.read_tv_setting)
    TextView mTvSetting;
    @BindView(R.id.auto_read_progress)
    ProgressBar mAutoReadProgressBar;
    @BindView(R.id.read_iv_auto_play)
    ImageView mIvAutoPlay;
    @BindView(R.id.read_tv_speed_minus)
    ImageView mTvSpeedMinus;
    @BindView(R.id.read_tv_speed_add)
    ImageView mTvSpeedAdd;
    @BindView(R.id.read_tv_speed)
    TextView mTvSpeed;
    @BindView(R.id.read_tv_auto_read_exit)
    TextView mTvAutoReadExit;
    /***************left slide*******************************/
    @BindView(R.id.read_iv_catalog)
    ListView mLvCategory;


//    @BindView(R.id.status_bar_view)
//    View mStatusBarView;
    /*****************view******************/
    private BookReadSettingDialog mSettingDialog;
    private PageLoader mPageLoader;
    private Animation mTopInAnim;
    private Animation mTopOutAnim;
    private Animation mBottomInAnim;
    private Animation mBottomOutAnim;
    private BookCatalogAdapter mBookCatalogAdapter;
    private CollectionMediaBean mCollectionMediaBean;
    private SiteSourceBean mSiteSourceBean;

    public static List<MediaChapterBean> inputChapterBeanList;
    private int inputChapterIndex = -1;
    private String inputChapterTitle = null;
    private int inputPage = 0;
    private boolean autoReading = false;
    private int autoReadSpeed = ReadSettingManager.getInstance().getAutoReadSpeed();
//    private ImmersionBar mImmersionBar;

    //控制屏幕常亮
    private PowerManager.WakeLock mWakeLock;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case WHAT_CATEGORY:
                    mLvCategory.setSelection(mPageLoader.getChapterPos());
                    break;
                case WHAT_CHAPTER:
                    mPageLoader.openChapter();
                    break;
                case WHAT_AUTO_READ_PROGRESS_ADD:
                    if (mAutoReadProgressBar == null) {
                        return;
                    }
                    int currentProgress = mAutoReadProgressBar.getProgress();
                    mAutoReadProgressBar.setProgress(currentProgress + 1);
                    if (currentProgress >= 1000) {
                        if (mPageLoader != null && mPageLoader.getPageStatus() !=
                                mPageLoader.STATUS_LOADING &&
                                mPageLoader.getPageStatus() != PageLoader.STATUS_ERROR &&
                                mPageLoader.getPageStatus() != PageLoader.STATUS_PARING) {
                            mPageLoader.skipToNextPage();
                        }
                        mAutoReadProgressBar.setProgress(0);
                    }
                    break;
            }
        }
    };
    // 接收电池信息和时间更新的广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra("level", 0);
                mPageLoader.updateBattery(level);
            }
            // 监听分钟的变化
            else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mPageLoader.updateTime();
            }
        }
    };

    // 亮度调节监听
    // 由于亮度调节没有 Broadcast 而是直接修改 ContentProvider 的。所以需要创建一个 Observer 来监听 ContentProvider 的变化情况。
    private ContentObserver mBrightObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange);

            // 判断当前是否跟随屏幕亮度，如果不是则返回
            if (selfChange || !mSettingDialog.isBrightFollowSystem()) return;

            // 如果系统亮度改变，则修改当前 Activity 亮度
            if (BRIGHTNESS_MODE_URI.equals(uri)) {
                Log.d(TAG, "亮度模式改变");
            } else if (BRIGHTNESS_URI.equals(uri) && !BrightnessUtils.isAutoBrightness(BookReadActivity.this)) {
                Log.d(TAG, "亮度模式为手动模式 值改变");
                BrightnessUtils.setBrightness(BookReadActivity.this, BrightnessUtils.getScreenBrightness(BookReadActivity.this));
            } else if (BRIGHTNESS_ADJ_URI.equals(uri) && BrightnessUtils.isAutoBrightness(BookReadActivity.this)) {
                Log.d(TAG, "亮度模式为自动模式 值改变");
                BrightnessUtils.setDefaultBrightness(BookReadActivity.this);
            } else {
                Log.d(TAG, "亮度调整 其他");
            }
        }
    };

    /***************params*****************/
    private boolean isCollected = false; // isFromSDCard
    private boolean isNightMode = false;
    private boolean isFullScreen = false;
    private boolean isRegistered = false;


    //    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
//                                       List<MediaChapterBean> beanList, boolean isCollected,
//                                       int chapterIndex, boolean recreate) {
//        if (recreate) {
//
//        }
//
//    }
    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
                                     List<MediaChapterBean> beanList, boolean isCollected,
                                     int chapterIndex) {
        startActivity(context, collectionMediaBean, beanList, isCollected, chapterIndex, null, 0);
    }

    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
                                     List<MediaChapterBean> beanList, boolean isCollected,
                                     int chapterIndex, String chapterTitle, int page) {

        inputChapterBeanList = beanList;
        context.startActivity(new Intent(context, BookReadActivity.class)
                        .putExtra(EXTRA_IS_IN_SHELF, isCollected)
                        .putExtra(EXTRA_SHELF_BOOK, collectionMediaBean)
//                .putExtra(EXTRA_CHAPTER_LIST, (Serializable) beanList)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_INDEX, chapterIndex)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_TITLE, chapterTitle)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_PAGE, page)

        );
    }


    @Override
    protected int getContentId() {
        return R.layout.activity_book_read;
    }

    @Override
    protected BookReadContract.Presenter bindPresenter() {
        return new BookReadPresenter();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

//        ReadSettingManager.getInstance().setAutoBrightness(true);

        mCollectionMediaBean = getIntent().getParcelableExtra(EXTRA_SHELF_BOOK);
        isCollected = getIntent().getBooleanExtra(EXTRA_IS_IN_SHELF, false);

//        inputChapterBeanList = (List<MediaChapterBean>) getIntent().getSerializableExtra(EXTRA_CHAPTER_LIST);
        inputChapterIndex = getIntent().getIntExtra(EXTRA_JUMP_TO_CHAPTER_INDEX, 0);
        inputChapterTitle = getIntent().getStringExtra(EXTRA_JUMP_TO_CHAPTER_TITLE);
        inputPage = getIntent().getIntExtra(EXTRA_JUMP_TO_CHAPTER_PAGE, 0);

        isNightMode = ReadSettingManager.getInstance().isNightMode();
        isFullScreen = ReadSettingManager.getInstance().isFullScreen();

        mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        mSiteSourceBean = mCollectionMediaBean.getSiteSourceBean();
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        //设置标题
//        toolbar.setTitle(mCollectionMediaBean.getTitle());
        if (null != getSupportActionBar()) {
            getSupportActionBar().setTitle(mCollectionMediaBean.getTitle());
        }
        //半透明化StatusBar
//        SystemBarUtils.transparentStatusBar(this);
    }

    @Override
    protected void initView() {
        super.initView();

        // 如果 API < 18 取消硬件加速
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mPvPage.setLayerType(LAYER_TYPE_SOFTWARE, null);
        }

        //获取页面加载器
        mPageLoader = mPvPage.getPageLoader(mCollectionMediaBean);
        //禁止滑动展示DrawerLayout
        mDlSlide.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        //侧边打开后，返回键能够起作用
        mDlSlide.setFocusableInTouchMode(false);
        mSettingDialog = new BookReadSettingDialog(this, mPageLoader);

        setUpAdapter();

        initNavigationBar();

        //夜间模式按钮的状态
        toggleNightMode();

        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mReceiver, intentFilter);

        //设置当前Activity的Brightness
        if (ReadSettingManager.getInstance().isBrightnessAuto()) {
            BrightnessUtils.setDefaultBrightness(this);
        } else {
            BrightnessUtils.setBrightness(this, ReadSettingManager.getInstance().getBrightness());
        }

        //初始化屏幕常亮类
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, ":keep bright");

        //隐藏StatusBar
        mPvPage.post(this::hideSystemBar);

        //初始化TopMenu
        initTopMenu();

        //初始化BottomMenu
        initBottomMenu();

//        SystemBarUtils.transparentStatusBar(this);
//        ImmersionBar.destroy(this, null);
//        SystemBarUtils.transparentStatusBar(this);
//        StatusBarCompat.compat(this, R.color.transparent);
//        //TODO 这里的原理不太懂
//        if (ImmersionBar.hasNotchScreen(this)) {
////            下面的fitSystemWindows和statusBarColor是为了让内容不和status bar重叠
//            ImmersionBar.with(this)
//                    .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
//                    .statusBarColor(R.color.black)
//                    .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
//                    .init();
//        }else {
////            ImmersionBar.destroy(this, null);
//        }

//        mImmersionBar = ImmersionBar.with(this);
//        StatusBarCompat.compat(this, R.color.read_bg_1);
//        mImmersionBar.fitsSystemWindows(true)
////                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
////                .statusBarColor(ReadSettingManager.getInstance().getPageStyle().getBgColor())
//                .statusBarColor(R.color.read_bg_1)
//                .init();
//        mDlSlide.setStatusBarBackground(ReadSettingManager.getInstance().getPageStyle().getBgColor());
//        mDlSlide.setStatusBarBackground(R.color.red);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
//        SystemBarUtils.transparentStatusBar(this);
//        mImmersionBar = ImmersionBar.with(this);
//        ImmersionBar.hideStatusBar(getWindow());
        //
//        mStatusBarView.setBackgroundColor(getResources().getColor(R.color.read_bg_1));
        ImmersionBar.with(this)
//                .fitsSystemWindows(true)
//                .fullScreen(true)
//                .statusBarView(mStatusBarView)
                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
//                .statusBarColor(ReadSettingManager.getInstance().getPageStyle().getBgColor())
//                .navigationBarColor(R.color.read_bg_1)
//                .statusBarColor(R.color.read_bg_1)
//                .navigationBarColor(R.color.read_bg_1)
                .init();

//        mReadWrapper.setBackgroundColor(ReadSettingManager.getInstance().getPageStyle().getBgColor());
//        mReadWrapper.setPadding(0,ImmersionBar.getStatusBarHeight(this),0,0);
//        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mReadWrapper.getLayoutParams());
//        lp.setMargins(lp.leftMargin, ImmersionBar.getStatusBarHeight(this), lp.rightMargin, lp.bottomMargin);
//        mReadWrapper.setLayoutParams(lp);

    }

    private void initTopMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            mAblTopMenu.setPadding(0, ScreenUtils.getStatusBarHeight(), 0, 0);
        }
    }

    private void initBottomMenu() {
        //判断是否全屏
        if (ReadSettingManager.getInstance().isFullScreen()) {
            //还需要设置mBottomMenu的底部高度
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
            params.bottomMargin = ScreenUtils.getNavigationBarHeight();
            mLlBottomMenu.setLayoutParams(params);
        } else {
            //设置mBottomMenu的底部距离
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
            params.bottomMargin = 0;
            mLlBottomMenu.setLayoutParams(params);
        }
        updateAutoReadSpeed();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Log.d(TAG, "onWindowFocusChanged: " + mAblTopMenu.getMeasuredHeight());
    }

    private void toggleNightMode() {
        if (isNightMode) {
            mTvNightMode.setText(StringUtils.getString(R.string.wa_mode_morning));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_read_menu_morning);
            mTvNightMode.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        } else {
            mTvNightMode.setText(StringUtils.getString(R.string.wa_mode_night));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_read_menu_night);
            mTvNightMode.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        }
    }

    private void setUpAdapter() {
        mBookCatalogAdapter = new BookCatalogAdapter();
        mLvCategory.setAdapter(mBookCatalogAdapter);
        mLvCategory.setFastScrollEnabled(true);
    }

    // 注册亮度观察者
    private void registerBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (!isRegistered) {
                    final ContentResolver cr = getContentResolver();
                    cr.unregisterContentObserver(mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_ADJ_URI, false, mBrightObserver);
                    isRegistered = true;
                }
            }
        } catch (Throwable throwable) {
            LogUtils.e(TAG, "register mBrightObserver error! " + throwable);
        }
    }

    //解注册
    private void unregisterBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (isRegistered) {
                    getContentResolver().unregisterContentObserver(mBrightObserver);
                    isRegistered = false;
                }
            }
        } catch (Throwable throwable) {
            LogUtils.e(TAG, "unregister BrightnessObserver error! " + throwable);
        }
    }

    private void initPageLoaderEvent() {

        mPageLoader.setOnPageChangeListener(
                new PageLoader.OnPageChangeListener() {

                    @Override
                    public void onChapterChange(int pos) {
                        mBookCatalogAdapter.setChapter(pos);
                    }

                    @Override
                    public void requestChapters(List<TxtChapter> requestChapters) {
                        mPresenter.loadChapter(mSiteSourceBean, mCollectionMediaBean.getId(), requestChapters);
                        mHandler.sendEmptyMessage(WHAT_CATEGORY);
                        //隐藏提示
                        mTvPageTip.setVisibility(GONE);
                    }

                    @Override
                    public void onCategoryFinish(List<TxtChapter> chapters) {
                        for (TxtChapter chapter : chapters) {
                            chapter.setTitle(StringUtils.convertCC(chapter.getTitle(), mPvPage.getContext()));
                        }
                        mBookCatalogAdapter.refreshItems(chapters);
                    }

                    @Override
                    public void onPageCountChange(int count) {
                        mSbChapterProgress.setMax(Math.max(0, count - 1));
                        mSbChapterProgress.setProgress(0);
                        // 如果处于错误状态，那么就冻结使用
                        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING
                                || mPageLoader.getPageStatus() == PageLoader.STATUS_ERROR) {
                            mSbChapterProgress.setEnabled(false);
                        } else {
                            mSbChapterProgress.setEnabled(true);
                        }
                    }

                    @Override
                    public void onPageChange(int pos) {
                        mSbChapterProgress.post(
                                () -> mSbChapterProgress.setProgress(pos)
                        );
                    }
                }
        );
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        initPageLoaderEvent();
        mSettingDialog.setListener(pageStyle -> {
            initImmersionBar();
        });

        mSbChapterProgress.setOnSeekBarChangeListener(
                new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (mLlBottomMenu.getVisibility() == VISIBLE) {
                            //显示标题
                            mTvPageTip.setText((progress + 1) + "/" + (mSbChapterProgress.getMax() + 1));
                            mTvPageTip.setVisibility(VISIBLE);
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        //进行切换
                        int pagePos = mSbChapterProgress.getProgress();
                        if (pagePos != mPageLoader.getPagePos()) {
                            mPageLoader.skipToPage(pagePos);
                        }
                        //隐藏提示
                        mTvPageTip.setVisibility(GONE);
                    }
                }
        );

        mPvPage.setTouchListener(new PageView.TouchListener() {
            @Override
            public boolean onTouch() {
                return !hideReadMenu();
            }

            @Override
            public void center() {
                toggleMenu(true);
            }

            @Override
            public void prePage() {
            }

            @Override
            public void nextPage() {
            }

            @Override
            public void cancel() {
            }
        });

        mLvCategory.setOnItemClickListener(
                (parent, view, position, id) -> {
                    mDlSlide.closeDrawer(GravityCompat.START);
                    mPageLoader.skipToChapter(position);
                }
        );

        mTvCategory.setOnClickListener(
                (v) -> {
                    //移动到指定位置
                    if (mBookCatalogAdapter.getCount() > 0) {
                        mLvCategory.setSelection(mPageLoader.getChapterPos());
                    }
                    //切换菜单
                    toggleMenu(true);
                    //打开侧滑动栏
                    mDlSlide.openDrawer(GravityCompat.START);
                }
        );
        mTvChangeSource.setOnClickListener(
                (v -> {

                    //TODO 先保存记录，方便换源的时候找到对应的章节定位
                    // 会多出没有收藏的章节信息，需要定时清理？
                    mPageLoader.saveRecord();
                    mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
                    //可能遇到还没加载好，就点击换源的，这里还没章节
                    String currentChapterName = "";
                    List<MediaChapterBean> chapterBeanList = mCollectionMediaBean.getMediaChapterList();
                    if (chapterBeanList != null && chapterBeanList.size() > 0) {
                        chapterBeanList.get(mPageLoader.getChapterPos()).getName();
                    }
                    ChangeSourceActivity.startActivityForResult(REQUEST_CHANGE_SOURCE, this, mCollectionMediaBean, currentChapterName, mPageLoader.getPagePos(), isCollected);
                })
        );
        mTvSetting.setOnClickListener(
                (v) -> {
                    mSettingDialog.show();
                    toggleMenu(false);
                }
        );

        mTvPreChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipPreChapter()) {
                        mBookCatalogAdapter.setChapter(mPageLoader.getChapterPos());
                    }
                }
        );

        mTvNextChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipNextChapter()) {
                        mBookCatalogAdapter.setChapter(mPageLoader.getChapterPos());
                    }
                }
        );

        mTvNightMode.setOnClickListener(
                (v) -> {
                    if (isNightMode) {
                        isNightMode = false;
                    } else {
                        isNightMode = true;
                    }
                    mPageLoader.setNightMode(isNightMode);
                    toggleNightMode();
                }
        );
        mTvDownload.setOnClickListener(
                (view -> {
                    showDownloadDialog();
                })
        );

        //TODO
//        mTvBrief.setOnClickListener(
//                (v) -> MediaDetailActivity.startActivity(this, mCollectionMediaBean, inputChapterBeanList)
//        );
//
//        mTvCommunity.setOnClickListener(
//                (v) -> {
//                    Intent intent = new Intent(this, CommunityActivity.class);
//                    startActivity(intent);
//                }
//        );

        mSettingDialog.setOnDismissListener(
                dialog -> hideSystemBar()
        );

        mIvAutoPlay.setOnClickListener(v -> {
            hideReadMenu();
            autoReading = true;
            mAutoReadProgressBar.setVisibility(VISIBLE);
            mAutoReadProgressBar.setMax(1000);
            mAutoReadProgressBar.setProgress(0);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (autoReading) {
                        mHandler.sendEmptyMessage(WHAT_AUTO_READ_PROGRESS_ADD);
                        mHandler.postDelayed(this, 100 / autoReadSpeed);
                    }
                }
            }, 100 / autoReadSpeed);
        });

        mTvSpeedMinus.setOnClickListener(v -> {
            if (autoReadSpeed <= AUTO_SPEED_MIN) {
                return;
            }
            autoReadSpeed -= 1;
            updateAutoReadSpeed();
        });

        mTvSpeedAdd.setOnClickListener(v -> {
            if (autoReadSpeed >= AUTO_SPEED_MAX) {
                return;
            }
            autoReadSpeed += 1;
            updateAutoReadSpeed();
        });

        mTvAutoReadExit.setOnClickListener(v -> {
            autoReading = false;
            mAutoReadProgressBar.setVisibility(GONE);
            mAutoReadMenu.setVisibility(GONE);
        });


    }

    private void updateAutoReadSpeed() {
        ReadSettingManager.getInstance().setAutoReadSpeed(autoReadSpeed);
        mTvSpeed.setText(autoReadSpeed + "");
    }

    private void showDownloadDialog() {
        String[] chapterChoice = new String[]{"后面50章", "后面全部章节", "全部章节"};
        new AlertDialog.Builder(this)
                .setTitle(R.string.wa_common_download_tip)
                .setItems(chapterChoice, ((dialogInterface, i) -> {
                    List<MediaChapterBean> chapterBeanList = new ArrayList<>();
                    mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
                    List<MediaChapterBean> chapterAll = mCollectionMediaBean.getMediaChapterList();
                    switch (i) {
                        case 0:
                            chapterBeanList.addAll(chapterAll.subList(mPageLoader.getChapterPos(),
                                    mPageLoader.getChapterPos() + 50 > chapterAll.size() ? chapterAll.size() : mPageLoader.getChapterPos() + 50));
                            break;
                        case 1:
                            chapterBeanList.addAll(chapterAll.subList(mPageLoader.getChapterPos(), chapterAll.size()));
                            break;
                        case 2:
                            chapterBeanList.addAll(chapterAll);
                            break;
                    }

                    DownloadTaskBean downloadTaskBean = new DownloadTaskBean();
                    downloadTaskBean.setTaskName(mCollectionMediaBean.getId());
                    downloadTaskBean.setCollectionMediaBean(mCollectionMediaBean);
                    downloadTaskBean.setMediaId(mCollectionMediaBean.getId());
                    downloadTaskBean.setBookChapters(chapterBeanList);
//                    downloadTaskBean.setLastChapter();

                    //先保存，才会保存章节，而且下载的，都需要先收藏 ,必须在setBookChapters后面，因为里面会给chapter设定task_name
                    MediaStorageManager.getInstance().updateCollectionMediaWithReplace(mCollectionMediaBean);

                    MediaStorageManager.getInstance().saveDownloadTask(downloadTaskBean);
                    RxBus.get().post(RxEvent.DOWNLOAD_TASK_ADD, downloadTaskBean);
                    startActivity(new Intent(this, DownloadActivity.class));


                })).show();
    }

    private void initNavigationBar() {
        PageStyle pageStyle = ReadSettingManager.getInstance().getPageStyle();

        SystemBarUtils.setNavigationBarColor(this, getResources().getColor(R.color.black));
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private boolean hideReadMenu() {
        hideSystemBar();
        if (mAblTopMenu.getVisibility() == VISIBLE) {
            toggleMenu(true);
            return true;
        } else if (mSettingDialog.isShowing()) {
            mSettingDialog.dismiss();
            return true;
        }
        return false;
    }

    private void showSystemBar() {
        //显示
        SystemBarUtils.showUnStableStatusBar(this);
        if (isFullScreen) {
            SystemBarUtils.showUnStableNavBar(this);
        }
    }

    private void hideSystemBar() {
        //隐藏
        SystemBarUtils.hideStableStatusBar(this);
        if (isFullScreen) {
            SystemBarUtils.hideStableNavBar(this);
        }
//        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
    }

    /**
     * 切换菜单栏的可视状态
     * 默认是隐藏的
     */
    private void toggleMenu(boolean hideStatusBar) {
        initMenuAnim();

//        ImmersionBar.with(this).hideBar(BarHide.FLAG_SHOW_BAR).init();
//        if (hideStatusBar) {
//            hideSystemBar();
//        }
        if (autoReading) {
            mAblTopMenu.setVisibility(GONE);
            mLlBottomMenu.setVisibility(GONE);
            mTvPageTip.setVisibility(GONE);
            mIvAutoPlay.setVisibility(GONE);
            if (mAutoReadMenu.getVisibility() == VISIBLE) {
                mAutoReadMenu.startAnimation(mBottomOutAnim);
                mAutoReadMenu.setVisibility(GONE);
            } else {
                mAutoReadMenu.startAnimation(mBottomInAnim);
                mAutoReadMenu.setVisibility(VISIBLE);
            }
            return;
        } else {
            mAutoReadProgressBar.setVisibility(GONE);
            mAutoReadMenu.setVisibility(GONE);
        }
        if (mAblTopMenu.getVisibility() == View.VISIBLE) {
            //关闭
            mAblTopMenu.startAnimation(mTopOutAnim);
            mLlBottomMenu.startAnimation(mBottomOutAnim);
            mIvAutoPlay.startAnimation(mBottomOutAnim);
            mAblTopMenu.setVisibility(GONE);
            mLlBottomMenu.setVisibility(GONE);
            mTvPageTip.setVisibility(GONE);
            mIvAutoPlay.setVisibility(GONE);

//            if (hideStatusBar) {
            hideSystemBar();
//            }
        } else {
            mAblTopMenu.setVisibility(View.VISIBLE);
            mLlBottomMenu.setVisibility(View.VISIBLE);
            mIvAutoPlay.setVisibility(VISIBLE);
            mAblTopMenu.startAnimation(mTopInAnim);
            mLlBottomMenu.startAnimation(mBottomInAnim);
            mIvAutoPlay.startAnimation(mBottomInAnim);

//            showSystemBar();
            hideSystemBar();
        }
    }

    //初始化菜单动画
    private void initMenuAnim() {
        if (mTopInAnim != null) return;

        mTopInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_in);
        mTopOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_out);
        mBottomInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_in);
        mBottomOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_out);
        //退出的速度要快
        mTopOutAnim.setDuration(200);
        mBottomOutAnim.setDuration(200);
    }

    @Override
    protected void startLogic() {

        super.startLogic();
        // 如果是已经收藏的，那么就从数据库中获取目录
//        List<MediaChapterBean> inputChapterBeanList = mCollectionMediaBean.getMediaChapterList();
        if (inputChapterBeanList != null && inputChapterBeanList.size() > 0) {
            showCatalog(inputChapterBeanList);
        } else {
            if (isCollected) {
                Disposable disposable = MediaStorageManager.getInstance()
                        .getMediaChaptersInRx(mCollectionMediaBean.getId())
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(
                                (mediaChapterBeanList, throwable) -> {
                                    if (mediaChapterBeanList == null || mediaChapterBeanList.isEmpty()) {
                                        //保存了都没找到;很可能是换源之后强行清除了
                                        mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
                                        return;
                                    }
                                    // 设置 CollBook
                                    mPageLoader.getShelfBook().setMediaChapterList(mediaChapterBeanList);
                                    // 刷新章节列表
                                    mPageLoader.refreshChapterList();
                                    // 如果是网络小说并被标记更新的，则从网络下载目录
                                    if (mCollectionMediaBean.getIfUpdated() && !mCollectionMediaBean.getIfLocal()) {
                                        mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
                                    }
                                    LogUtils.e(throwable);
                                }
                        );
                addDisposable(disposable);
            } else {
                // 从网络中获取目录
                mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
            }
        }
    }

    /***************************view************************************/
    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    private int getMatchedChapterIndex(List<MediaChapterBean> mediaChapterBeanList) {

        double similar = 0.0d;
        int similarIndex = 0;

        for (int i = 0; i < mediaChapterBeanList.size(); i++) {
            MediaChapterBean chapterBean = mediaChapterBeanList.get(i);
            String tempChapterTitle = chapterBean.getName().trim();
            if (tempChapterTitle.equals(inputChapterTitle)) {
                return i;
            }
            double tmpSim = SimilarityUtil.sim(inputChapterTitle.replaceAll("[第章话回話🔐]", ""), tempChapterTitle.replaceAll("[第章回话話🔐]",""));
            //如果相似度接近，那么用索引值更接近的那个
            if (tmpSim > similar || ((tmpSim == similar) && Math.abs(i - inputChapterIndex) < Math.abs(i - similarIndex))) {
                similar = tmpSim;
                similarIndex = i;
            }
        }
        return similarIndex;

    }

    @Override
    public void showCatalog(List<MediaChapterBean> bookChapters) {
        LogUtils.d("showCatalog , bookChapters = " + bookChapters);
        mPageLoader.getShelfBook().setMediaChapterList(bookChapters);
        //认定inputChapterTitle 和 inputChapterIndex 只会有一个起作用，如果title有了，
        //那么index就没有，用title来生成它
        if (inputChapterTitle != null) {
            inputChapterIndex = getMatchedChapterIndex(bookChapters);
        }
        MediaRecordBean recordBean = MediaStorageManager.getInstance().getMediaRecord(mCollectionMediaBean.getId());
        if (recordBean == null) {
            recordBean = new MediaRecordBean();
            recordBean.setMediaId(mCollectionMediaBean.getId());
        }
        recordBean.setChapter(inputChapterIndex);
        recordBean.setPagePos(inputPage);
        MediaStorageManager.getInstance().saveMediaRecord(recordBean);
        if (inputChapterIndex >= 0) {
            //用上面保存的阅读记录，重新初始化书籍
            mPageLoader.prepareBook();
            mPageLoader.refreshChapterListAndJumpToChapter(inputChapterIndex);
        } else {
            mPageLoader.refreshChapterList();
        }

        // 如果是目录更新的情况，那么就需要存储更新数据
        if (mCollectionMediaBean.getIfUpdated() && isCollected) {
            MediaStorageManager.getInstance()
                    .saveMediaChaptersWithAsync(bookChapters);
        }
    }

    @Override
    public void finishChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mHandler.sendEmptyMessage(WHAT_CHAPTER);
        }
        // 当完成章节的时候，刷新列表
        mBookCatalogAdapter.notifyDataSetChanged();
    }

    @Override
    public void errorChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mPageLoader.chapterError();
        }
    }

    @Override
    public void onBackPressed() {
        if (mAblTopMenu.getVisibility() == View.VISIBLE) {
            // 非全屏下才收缩，全屏下直接退出
            if (!ReadSettingManager.getInstance().isFullScreen()) {
                toggleMenu(true);
                return;
            }
        } else if (mSettingDialog.isShowing()) {
            mSettingDialog.dismiss();
            return;
        }
        else if (mDlSlide.isDrawerOpen(GravityCompat.START)) {
            mDlSlide.closeDrawer(GravityCompat.START);
            return;
        }

        mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        if (!mCollectionMediaBean.getIfLocal() && !isCollected
                && !mCollectionMediaBean.getMediaChapterList().isEmpty()) {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("加入书架")
                    .setMessage("喜欢本书就加入书架吧")
                    .setPositiveButton("确定", (dialog, which) -> {
                        //设置为已收藏
                        isCollected = true;
                        //设置阅读时间
                        mCollectionMediaBean.setLastRead(StringUtils.
                                dateConvert(System.currentTimeMillis(), WaConstants.FORMAT_BOOK_DATE));

                        MediaStorageManager.getInstance()
                                .saveCollectionMediaWithAsync(mCollectionMediaBean);
                        RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, mCollectionMediaBean);

                        exit();
                    })
                    .setNegativeButton("取消", (dialog, which) -> {
                        exit();
                    }).create();
            alertDialog.show();
        } else {
            exit();
        }
    }

    // 退出
    private void exit() {
        Intent result = new Intent();
        result.putExtra(MediaDetailActivity.RESULT_IS_COLLECTED, isCollected);
        setResult(Activity.RESULT_OK, result);
        // 退出
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerBrightObserver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWakeLock.acquire();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWakeLock.release();
        if (isCollected) {
            mPageLoader.saveRecord();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterBrightObserver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);

        mHandler.removeMessages(WHAT_CATEGORY);
        mHandler.removeMessages(WHAT_CHAPTER);

        mPageLoader.closeBook();
        mPageLoader = null;

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean isVolumeTurnPage = ReadSettingManager
                .getInstance().isVolumeTurnPage();
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (isVolumeTurnPage) {
                    return mPageLoader.skipToPrePage();
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (isVolumeTurnPage) {
                    return mPageLoader.skipToNextPage();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            LogUtils.e("BookReadActivity onActivityResult ,resultCode not ok, is " + resultCode);
            return;
        }
//        SystemBarUtils.hideStableStatusBar(this);
        if (requestCode == REQUEST_MORE_SETTING) {
            boolean fullScreen = ReadSettingManager.getInstance().isFullScreen();
            if (isFullScreen != fullScreen) {
                isFullScreen = fullScreen;
                // 刷新BottomMenu
                initBottomMenu();
            }

            // 设置显示状态
            if (isFullScreen) {
//                SystemBarUtils.hideStableNavBar(this);
            } else {
//                SystemBarUtils.showStableNavBar(this);
            }
        } else if (requestCode == REQUEST_CHANGE_TYPEFACE) {
            String typefaceFilePath = data.getStringExtra("data");
            if (mPageLoader != null) {
                mPageLoader.setTypeface(typefaceFilePath);
            }
        } else if (requestCode == REQUEST_CHANGE_SOURCE) {
            //先删除老的
            hideReadMenu();
            mBookCatalogAdapter.clear();

            inputChapterIndex = mPageLoader.getChapterPos();
            inputChapterTitle = mPageLoader.getChapterTitle();
//            mPageLoader.closeBook();

            MediaStorageManager.getInstance().deleteCollBook(mCollectionMediaBean);
            //再制作新的
            mCollectionMediaBean = data.getParcelableExtra("bean");
            mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
            mSiteSourceBean = mCollectionMediaBean.getSiteSourceBean();
            mPageLoader = mPvPage.newPageLoader(mCollectionMediaBean);
            initPageLoaderEvent();
//            mPageLoader.setCollectionMediaBean(mCollectionMediaBean);
            mCollectionMediaBean.setMediaChapterList(new ArrayList<>());
            MediaStorageManager.getInstance().saveCollectionMedia(mCollectionMediaBean);
            RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, mCollectionMediaBean);
            inputChapterBeanList = null;
//            mPageLoader.setPageStatus(PageLoader.STATUS_LOADING);
            startLogic();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reader, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_detail) {
            mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
            MediaDetailActivity.startActivity(this, mCollectionMediaBean, mCollectionMediaBean.getMediaChapterList());
        } else if (id == R.id.action_view_by_browser) {
            if (mCollectionMediaBean == null || mCollectionMediaBean.getMediaChapterList().isEmpty() || mPageLoader == null) {
                return true;
            }
            openUrl(mCollectionMediaBean.getMediaChapterList().get(mPageLoader.getChapterPos()).getLink());
        }
        return super.onOptionsItemSelected(item);
    }

    public void openUrl(String url) {
        Intent intent = new Intent();
        intent.setData(Uri.parse(url));//Url 就是你要打开的网址
        intent.setAction(Intent.ACTION_VIEW);
        this.startActivity(intent); //启动浏览器
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initImmersionBar();
    }
}
